package com.presto.directo.mvvm.view

import ai.advance.liveness.lib.LivenessResult
import ai.advance.liveness.sdk.activity.LivenessActivity
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.view.isVisible
import androidx.recyclerview.widget.*
import com.presto.directo.*
import com.presto.directo.base.BaseActivity
import com.presto.directo.databinding.ActivityCardListBinding
import com.presto.directo.mvvm.adapter.CardListAdapter
import com.presto.directo.net.*
import com.presto.directo.utils.*
import java.io.*

class CardListActivity : BaseActivity() {

    private val binding by lazy { ActivityCardListBinding.inflate(layoutInflater) }
    private var showIndicator = true
    private var fromConfirm = false
    private lateinit var cardListAdapter: CardListAdapter
    private val locationUtil by lazy { LocationUtil() }
    private var liveness = false

    private val launchLive = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode != RESULT_OK) return@registerForActivityResult
        if (LivenessResult.isSuccess() && LivenessResult.getLivenessBitmap() != null) {
            start(onNext = {
                val bitmap = LivenessResult.getLivenessBitmap()
                val path = externalCacheDir?.path + File.separator + System.currentTimeMillis() + ".jpg"
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, FileOutputStream(File(path)))
                toLoan(path)
            }, onError = {
                toLoan()
            })
        } else {
            toast(LivenessResult.getErrorMsg())
        }
    }

    private fun toLoan(path: String = "") {
        val intent = Intent(this, LoanActivity::class.java)
        intent.putExtra("card", cardListAdapter.getItem(cardListAdapter.index))
        if (path.isNotEmpty()) {
            intent.putExtra("path", path)
        }
        startActivity(intent)
        finish()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Af.show_card_list_page.track(this)
        showIndicator = intent.getBooleanExtra("showIndicator", true)
        fromConfirm = intent.getBooleanExtra("fromConfirm", false)
        binding.progress.isVisible = showIndicator
        binding.btnNext.isVisible = showIndicator
        cardListAdapter = CardListAdapter(R.layout.item_card_list, showIndicator || fromConfirm)
        binding.rvCard.layoutManager = LinearLayoutManager(this).apply { orientation = RecyclerView.VERTICAL }
        cardListAdapter.addChildClickViewIds(R.id.iv_select, R.id.iv_delete)
        cardListAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_select -> selectCard(position)
                R.id.iv_delete -> deleteCard(position)
            }

        }
        binding.rvCard.adapter = cardListAdapter
        getCardList()
        start(onNext = {
            if (!BuildConfig.DEBUG) {
                liveness = getApiService().getConfig(getHttpMap().sign(2)).result?.live_open == "1"
            }
        }, toast = false)
    }

    override fun initEvent() {
        binding.btnAdd.setOnClickListener {
            launcher.launch(Intent(this, CardAddActivity::class.java))
        }
        binding.btnNext.setOnClickListener {
            if (cardListAdapter.index < 0 || cardListAdapter.index >= cardListAdapter.data.size) {
                toast("Favor de seleccionar una tarjeta bancaria")
                return@setOnClickListener
            }
            Af.click_select_card_next.track(this)
            if (liveness) {
                launchLive.launch(Intent(this, LivenessActivity::class.java))
            } else {
                toLoan()
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun selectCard(position: Int) {
        cardListAdapter.index = position
        cardListAdapter.notifyDataSetChanged()
        updateBtn()
        if (fromConfirm) {
            val intent = Intent()
            intent.putExtra("card", cardListAdapter.getItem(position))
            setResult(RESULT_OK, intent)
            finish()
        }
    }

    private fun deleteCard(position: Int) {
        start(onNext = {
            showProgress()
            val map = getHttpMap()
            map["bank_id"] = cardListAdapter.getItem(position).bank_id
            getApiService().deleteCard(map.sign(19)).getResultOrNull()
            cardListAdapter.index = -1
            cardListAdapter.remove(cardListAdapter.getItem(position))
            updateBtn()
        }, onComplete = {
            dismissProgress()
        })
    }

    private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode != RESULT_OK) return@registerForActivityResult
        getCardList()
    }

    private fun getCardList() {
        start(onNext = {
            showProgress()
            getApiService().getCards(getHttpMap().sign(21)).getResultOrNull()?.let {
                cardListAdapter.data.clear()
                cardListAdapter.addData(it)
            }
        }, onComplete = {
            dismissProgress()
            updateBtn()
        })
    }

    override fun updateBtn() {
        binding.btnNext.isEnabled = !cardListAdapter.data.isNullOrEmpty()
    }

    override fun onDestroy() {
        super.onDestroy()
        locationUtil.stopLocation()
    }

    override val rootView: View
        get() = binding.root
}